<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { formSchema } from "./data"
  import { saveOrUpdateMpTag } from "./api"
  import { useMessage } from "/@/hooks/web/useMessage"

  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const accountId = ref("")
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 60,
    wrapperCol: {
      md: { span: 21 },
      sm: { span: 21 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    isUpdate.value = !!data?.isUpdate
    accountId.value = data.accountId
    setDrawerProps({ confirmLoading: false })
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      })
    }
    //禁用表单
    setProps({ disabled: !attrs.showFooter })
  })
  /**
   * 标题
   */
  const getTitle = computed(() => (!unref(isUpdate) ? "新增标签" : "编辑标签"))
  /**
   * 提交
   */
  async function handleSubmit() {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })
      //提交表单
      await saveOrUpdateMpTag({ ...values, accountId: unref(accountId) }, isUpdate.value)
      closeDrawer()
      emit("success")
      createMessage.success(`${getTitle.value}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
